import { requestAPI } from '@/api/commonRequest'
import apis from './api'

function dataAddIndex(rows) {
  if (!Array.isArray(rows)) return
  rows.forEach((row, index) => {
    if (!('index' in row)) row['index'] = index
  })
  return rows
}

// 获取仓库数据
export function getStoreData() {
  return requestAPI({
    apiUrl: apis.queryOtherOutboundApplicationInfoUsingPOST.APIUrl,
    variables: { warehouseId: this.leftCurRow['warehouseId'] }
  }).then(response => {
    if (response.result === '1') {
      this.leftTableData = dataAddIndex(response.rows)
    } else {
      this.$message(response.msg)
    }
  }).catch(err => {
    if (err.response.data.msg) {
      this.$message(err.response.data.msg)
    } else {
      this.$message(err.message)
    }
  }).finally(() => {
    this.tableLoadingL = false
  })
}

// 获仓库数据
export function SaveStoreData(loading) {
  let f = {
    ...this.leftFormFields
  }
  if (this.curIndex !== null) {
    f['warehouseId'] = this.leftCurRow['warehouseId']
  }
  return requestAPI({
    apiUrl: apis.saveDlrPartWarehouseUsingPOST.APIUrl,
    variables: f
  }).then(response => {
    if (response.result === '1') {
      this.$message('保存成功！')
      // 刷新 仓库表
      getStoreData.call(this)
    } else {
      this.$message(response.msg)
    }
  }).catch(err => {
    if (err.response.data.msg) {
      this.$message(err.response.data.msg)
    } else {
      this.$message(err.message)
    }
  }).finally(() => {
    loading.close()
  })
}
// 根据仓库获取 仓位数据
export function getPosDataByStore(row) {
  return requestAPI({
    apiUrl: apis.queryDlrPartWareSpaceInfoUsingPOST.APIUrl,
    variables: {
      warehouseId: row['warehouseId']
    }
  }).then(response => {
    if (response.result === '1') {
      this.rightTableData = dataAddIndex(response.rows)
    } else {
      this.$message(response.msg)
    }
  }).catch(err => {
    // loading.close()
    if (err.response.data.msg) {
      this.$message(err.response.data.msg)
    } else {
      this.$message(err.message)
    }
  }).finally(() => {
    this.tableLoadingR = false
  })
}

// 删除仓位
export function delStorePos() {
  return requestAPI({
    apiUrl: apis.deleteDlrPartWareSpaceUsingPOST.APIUrl,
    variables: this.selectData
  }).then(response => {
    // eslint-disable-next-line no-empty
    if (response.result === '1') {
      this.$message(response.msg || '仓位删除成功！')
      getPosDataByStore.call(this, this.leftCurRow)
      getStoreData.call(this)
      this.resetAddrData()
    } else {
      this.$message(response.msg || '仓位删除失败！')
    }
  }).catch(err => {
    // loading.close()
    if (err.response.data.msg) {
      this.$message(err.response.data.msg)
    } else {
      this.$message(err.message)
    }
  })
}
